package com.song.support.filter;

import cn.hutool.core.util.ObjectUtil;
import com.song.common.domain.vo.LoginUserVO;
import com.song.common.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

// 该接口在请求前执行一次，获取request中的数据，其中token就在请求头里
// 获取token，根据token从Redis中获取用户信息
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;

    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        LoginUserVO loginUserVO = jwtUtil.getLoginUser(request);
        // 判断是否为空
        if (ObjectUtil.isNotNull(loginUserVO)) {
            // 鉴权，跳转的时候需要访问 /index 页面
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserVO, null, loginUserVO.getAuthorities());
            // 将用户信息存储到SecurityContext中，SecurityContext存储到SecurityContextHolder中
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        // 放行（不管是否登录）交由后面的过滤器执行。如果没有登录，就会被登录拦截器拦截到
        filterChain.doFilter(request, response);
    }
}
